package com.meirengu.webview.service.impl;

import com.meirengu.common.RedisClient;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.webview.service.SmsService;
import com.meirengu.webview.utils.ConfigUtil;
import com.meirengu.webview.utils.MailUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 验证码服务实现类
 *
 * @author Marvin
 * @create 2017-01-12 下午7:24
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);

    @Autowired
    private RedisClient redisClient;


    public String SMS(String postData, String postUrl) throws Exception {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (Exception e) {
            logger.error("SmsServiceImpl.SMS postData :{} throws Exceprion :{}", postData, e.getMessage());
            //当有验证码获取失败时告警
            redisClient.lpush("smsErrorRedis", postData);
            String code = postData.substring(4, 7);
            if (code.equals("992")) {
                String phone = postData.substring(21, 32);
                redisClient.sadd("smsErrorPhone", phone);
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = df.format(new Date());
            String mailBody = "短信告警--" + now + "有短信发送失败：" + e.getMessage();
            MailUtil.sendMail("a1085227253@163.com", "短信告警", mailBody, false, null);
            MailUtil.sendMail("15835132986@139.com", "短信告警", mailBody, false, null);
            MailUtil.sendMail("15110299053@139.com", "短信告警", mailBody, false, null);
            MailUtil.sendMail("15000020953@139.com", "短信告警", mailBody, false, null);
            throw e;
        }
    }

    /**
     * 发送普通短信
     *
     * @param mobile
     * @param text
     * @return
     * @throws Exception
     */
    public Result singleSend(String mobile, String text) throws Exception {
        Result result = new Result();
        logger.info("SmsServiceImpl.singleSend params >> mobile:{}, text:{}", new Object[]{mobile, text});
        String domain = ConfigUtil.getConfig("SMS_DOMAIN");
        String uid = ConfigUtil.getConfig("SMS_UID");
        String pw = ConfigUtil.getConfig("SMS_PW");
        String PostData = "uid=" + uid + "&pw=" + pw + "&mb=" + mobile + "&ms=" + java.net.URLEncoder.encode(text, "utf-8");
        String ret = SMS(PostData, "http://" + domain + "/send.do");
        logger.info(ret);
        if (StringUtils.isNotBlank(ret)) {
            if (ret.contains(",")) {
                String[] retarr = ret.split(",");
                int code = Integer.parseInt(retarr[0]);
                if (code == 0) {
                    result.setCode(StatusCode.OK);
                    result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
                }
            }

        }
        return result;
    }

    /**
     * 发送关注微信短信
     *
     * @param mobile
     * @param text
     * @return
     * @throws Exception
     */
    public Result singleFollowSend(String mobile, String text) throws Exception {
        Result result = new Result();
        logger.info("SmsServiceImpl.singleFollowSend params >> mobile:{}, text:{}", new Object[]{mobile, text});
        String domain = ConfigUtil.getConfig("FOLLOW_SMS_DOMAIN");
        String uid = ConfigUtil.getConfig("FOLLOW_SMS_UID");
        String pw = ConfigUtil.getConfig("FOLLOW_SMS_PW");
        String PostData = "uid=" + uid + "&pw=" + pw + "&mb=" + mobile + "&ms=" + java.net.URLEncoder.encode(text, "utf-8");
        String ret = SMS(PostData, "http://" + domain + "/send.do");
        logger.info(ret);
        if (StringUtils.isNotBlank(ret)) {
            if (ret.contains(",")) {
                String[] retarr = ret.split(",");
                int code = Integer.parseInt(retarr[0]);
                if (code == 0) {
                    result.setCode(StatusCode.OK);
                    result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
                }
            }

        }
        return result;
    }

    /**
     * 发送营销短信
     *
     * @param mobile
     * @param text
     * @return
     * @throws Exception
     */
    public Result singleSendMarketing(String mobile, String text) throws Exception {
        Result result = new Result();
        logger.info("SmsServiceImpl.singleSendMarketing params >> mobile:{}, text:{}", new Object[]{mobile, text});
        String domain = ConfigUtil.getConfig("MSMS_DOMAIN");
        String uid = ConfigUtil.getConfig("MSMS_UID");
        String pw = ConfigUtil.getConfig("MSMS_PW");
        String PostData = "uid=" + uid + "&pw=" + pw + "&mb=" + mobile + "&ms=" + java.net.URLEncoder.encode(text, "utf-8");
        String ret = SMS(PostData, "http://" + domain + "/send.do");
        logger.info(ret);
        if (StringUtils.isNotBlank(ret)) {
            if (ret.contains(",")) {
                String[] retarr = ret.split(",");
                int code = Integer.parseInt(retarr[0]);
                if (code == 0) {
                    result.setCode(StatusCode.OK);
                    result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
                }
            }

        }
        return result;
    }

    /**
     * 查看列表内所有请求验证码异常的手机号
     */

    public Result showErrorMobile() throws Exception {
        Result result = new Result();
        Set<String> set = redisClient.sdiff("smsErrorPhone", "kwdRegister");
        if (set != null && set.size() > 0) {
            result.setCode(StatusCode.OK);
            result.setMsg("成功");
            result.setData(set.toString());
        } else {
            result.setCode(StatusCode.OK);
            result.setMsg("暂无记录");
        }

        return result;
    }


}
